/*
 * @Author: Await
 * @Date: 2025-05-06 17:40:35
 * @LastEditors: Await
 * @LastEditTime: 2025-05-06 17:40:35
 * @Description: 主题系列配置组件
 */
import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Typography,
  ColorPicker,
  Divider,
  InputNumber,
  Select,
  Card,
  Tooltip,
  Switch,
  Tabs,
  Radio,
  Space,
  Input,
  Button,
  Modal,
  message,
} from 'antd';
import { SaveOutlined, QuestionCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { defaultPresets, saveUserPreset, getAllPresets } from './presets';
import type { ThemeConfig } from '../../../types/chartTypes';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { Group, Button: RadioButton } = Radio;

interface SeriesConfigProps {
  value: ThemeConfig;
  onChange: (newValue: any) => void;
}

/**
 * 主题系列配置组件
 * 配置各种图表类型的系列样式
 */
const SeriesConfig: React.FC<SeriesConfigProps> = ({ value, onChange }) => {
  const [chartType, setChartType] = useState<string>('line');
  const [isPresetModalVisible, setIsPresetModalVisible] = useState<boolean>(false);
  const [presetName, setPresetName] = useState<string>('');
  const [activePreset, setActivePreset] = useState<string | null>(null);
  const [presets, setPresets] = useState(getAllPresets());

  // 加载预设列表
  useEffect(() => {
    setPresets(getAllPresets());
  }, []);

  // 应用预设
  const applyPreset = (presetName: string) => {
    const preset = presets.find(p => p.name === presetName);
    if (preset) {
      // 根据当前选中的图表类型应用相应的预设配置
      const configToApply = preset.config[chartType];
      if (configToApply) {
        onChange({
          ...value,
          [chartType]: {
            ...(value[chartType] || {}),
            ...configToApply
          }
        });
        message.success(`已应用预设: ${presetName}`);
        setActivePreset(presetName);
      } else {
        message.warning(`预设 ${presetName} 没有包含 ${chartType} 图表的配置`);
      }
    }
  };

  // 保存当前配置为新预设
  const handleSavePreset = () => {
    if (!presetName.trim()) {
      message.error('请输入预设名称');
      return;
    }
    
    const currentConfig = value[chartType];
    if (!currentConfig) {
      message.error('当前没有可保存的配置');
      return;
    }
    
    // 创建并保存新预设
    const newPreset = {
      name: presetName.trim(),
      config: {
        [chartType]: { ...currentConfig }
      }
    };
    
    saveUserPreset(newPreset);
    setPresets(getAllPresets());
    message.success('预设保存成功');
    setIsPresetModalVisible(false);
    setPresetName('');
  };

  // 初始化配置
  const lineConfig = value.line || {
    symbol: 'emptyCircle',
    symbolSize: 4,
    smooth: false,
    lineStyle: {
      width: 2,
      type: 'solid',
    },
  };

  const barConfig = value.bar || {
    barWidth: '40%',
    barGap: '30%',
    itemStyle: {
      barBorderWidth: 0,
      barBorderRadius: 0,
    },
  };

  const pieConfig = value.pie || {
    borderWidth: 2,
    borderRadius: 0,
    label: {
      color: '#333',
    },
  };

  const scatterConfig = value.scatter || {
    symbol: 'circle',
    symbolSize: 10,
  };

  const radarConfig = value.radar || {
    symbolSize: 4,
    lineStyle: {
      width: 2,
    },
    areaStyle: {
      opacity: 0.2,
    },
  };

  const mapConfig = value.map || {
    itemStyle: {
      areaColor: '#ddd',
      borderColor: '#eee',
      borderWidth: 0.5,
    },
    label: {
      color: '#000',
    },
    emphasis: {
      itemStyle: {
        areaColor: '#fe994e',
        borderColor: '#fff',
        borderWidth: 1,
      },
      label: {
        color: '#fff',
      },
    },
  };

  const candlestickConfig = value.candlestick || {
    itemStyle: {
      color: '#eb5454',
      color0: '#47b262',
      borderColor: '#eb5454',
      borderColor0: '#47b262',
      borderWidth: 1,
    },
  };

  const graphConfig = value.graph || {
    symbolSize: 10,
    itemStyle: {
      borderWidth: 1.5,
    },
    lineStyle: {
      width: 1.5,
      curveness: 0.3,
    },
    label: {
      color: '#333',
    },
  };

  // 更新折线图配置
  const updateLineConfig = (key: string, val: any) => {
    if (key.includes('.')) {
      const [mainKey, subKey] = key.split('.');
      onChange({
        ...value,
        line: {
          ...lineConfig,
          [mainKey]: {
            ...(lineConfig[mainKey] || {}),
            [subKey]: val,
          },
        },
      });
    } else {
      onChange({
        ...value,
        line: {
          ...lineConfig,
          [key]: val,
        },
      });
    }
  };

  // 更新柱状图配置
  const updateBarConfig = (key: string, val: any) => {
    if (key.includes('.')) {
      const [mainKey, subKey] = key.split('.');
      onChange({
        ...value,
        bar: {
          ...barConfig,
          [mainKey]: {
            ...(barConfig[mainKey] || {}),
            [subKey]: val,
          },
        },
      });
    } else {
      onChange({
        ...value,
        bar: {
          ...barConfig,
          [key]: val,
        },
      });
    }
  };

  // 更新饼图配置
  const updatePieConfig = (key: string, val: any) => {
    if (key.includes('.')) {
      const [mainKey, subKey] = key.split('.');
      onChange({
        ...value,
        pie: {
          ...pieConfig,
          [mainKey]: {
            ...(pieConfig[mainKey] || {}),
            [subKey]: val,
          },
        },
      });
    } else {
      onChange({
        ...value,
        pie: {
          ...pieConfig,
          [key]: val,
        },
      });
    }
  };

  // 更新散点图配置
  const updateScatterConfig = (key: string, val: any) => {
    onChange({
      ...value,
      scatter: {
        ...scatterConfig,
        [key]: val,
      },
    });
  };

  // 更新雷达图配置
  const updateRadarConfig = (key: string, val: any) => {
    if (key.includes('.')) {
      const [mainKey, subKey] = key.split('.');
      onChange({
        ...value,
        radar: {
          ...radarConfig,
          [mainKey]: {
            ...(radarConfig[mainKey] || {}),
            [subKey]: val,
          },
        },
      });
    } else {
      onChange({
        ...value,
        radar: {
          ...radarConfig,
          [key]: val,
        },
      });
    }
  };

  // 渲染折线图配置
  const renderLineConfig = () => (
    <Card title="折线图样式" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Text>
            图形标记
            <Tooltip title="折线上数据点的图形">
              <InfoCircleOutlined style={{ marginLeft: 8, fontSize: 14 }} />
            </Tooltip>
          </Text>
          <Select
            value={lineConfig.symbol || 'emptyCircle'}
            onChange={(val) => updateLineConfig('symbol', val)}
            style={{ width: '100%' }}
          >
            <Option value="circle">实心圆</Option>
            <Option value="emptyCircle">空心圆</Option>
            <Option value="rect">实心矩形</Option>
            <Option value="emptyRect">空心矩形</Option>
            <Option value="roundRect">实心圆角矩形</Option>
            <Option value="emptyRoundRect">空心圆角矩形</Option>
            <Option value="triangle">实心三角形</Option>
            <Option value="emptyTriangle">空心三角形</Option>
            <Option value="diamond">实心菱形</Option>
            <Option value="emptyDiamond">空心菱形</Option>
            <Option value="pin">实心水滴</Option>
            <Option value="emptyPin">空心水滴</Option>
            <Option value="arrow">实心箭头</Option>
            <Option value="emptyArrow">空心箭头</Option>
            <Option value="none">无</Option>
          </Select>
        </Col>
        <Col span={8}>
          <Text>标记大小</Text>
          <InputNumber
            value={lineConfig.symbolSize || 4}
            onChange={(val) => updateLineConfig('symbolSize', val)}
            min={1}
            max={20}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>平滑曲线</Text>
          <div>
            <Switch
              checked={lineConfig.smooth || false}
              onChange={(val) => updateLineConfig('smooth', val)}
            />
          </div>
        </Col>
      </Row>

      <Divider style={{ margin: '16px 0' }} />

      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Title level={5}>线条样式</Title>
        </Col>
        <Col span={8}>
          <Text>线宽</Text>
          <InputNumber
            value={lineConfig.lineStyle?.width || 2}
            onChange={(val) => updateLineConfig('lineStyle.width', val)}
            min={1}
            max={10}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>线型</Text>
          <Select
            value={lineConfig.lineStyle?.type || 'solid'}
            onChange={(val) => updateLineConfig('lineStyle.type', val)}
            style={{ width: '100%' }}
          >
            <Option value="solid">实线</Option>
            <Option value="dashed">虚线</Option>
            <Option value="dotted">点线</Option>
          </Select>
        </Col>
      </Row>
    </Card>
  );

  // 渲染柱状图配置
  const renderBarConfig = () => (
    <Card title="柱状图样式" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Text>
            柱宽
            <Tooltip title="柱子的宽度，可以是绝对值或百分比">
              <InfoCircleOutlined style={{ marginLeft: 8, fontSize: 14 }} />
            </Tooltip>
          </Text>
          <Input
            value={barConfig.barWidth || '40%'}
            onChange={(e) => updateBarConfig('barWidth', e.target.value)}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>
            柱间距
            <Tooltip title="不同系列柱子之间的间距，可以是绝对值或百分比">
              <InfoCircleOutlined style={{ marginLeft: 8, fontSize: 14 }} />
            </Tooltip>
          </Text>
          <Input
            value={barConfig.barGap || '30%'}
            onChange={(e) => updateBarConfig('barGap', e.target.value)}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>边框宽度</Text>
          <InputNumber
            value={barConfig.itemStyle?.barBorderWidth || 0}
            onChange={(val) => updateBarConfig('itemStyle.barBorderWidth', val)}
            min={0}
            max={10}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>圆角半径</Text>
          <InputNumber
            value={barConfig.itemStyle?.barBorderRadius || 0}
            onChange={(val) => updateBarConfig('itemStyle.barBorderRadius', val)}
            min={0}
            max={20}
            style={{ width: '100%' }}
          />
        </Col>
      </Row>
    </Card>
  );

  // 渲染饼图配置
  const renderPieConfig = () => (
    <Card title="饼图样式" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Text>边框宽度</Text>
          <InputNumber
            value={pieConfig.borderWidth || 2}
            onChange={(val) => updatePieConfig('borderWidth', val)}
            min={0}
            max={10}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>圆角半径</Text>
          <InputNumber
            value={pieConfig.borderRadius || 0}
            onChange={(val) => updatePieConfig('borderRadius', val)}
            min={0}
            max={20}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>标签颜色</Text>
          <div>
            <ColorPicker
              value={
                typeof pieConfig.label?.color === 'object' && pieConfig.label?.color?.colorStops?.[0]?.color 
                || (typeof pieConfig.label?.color === 'string' ? pieConfig.label.color : '#333')
              }
              onChange={(color) => {
                // 处理可能的颜色对象
                const colorString = typeof color === 'string' ? color : (color.toHexString ? color.toHexString() : String(color));
                updatePieConfig('label.color', colorString);
              }}
              showText
            />
            {typeof pieConfig.label?.color === 'object' && (
              <Tooltip title="当前为渐变色，颜色选择器仅显示主色调。修改将覆盖为纯色。">
                <InfoCircleOutlined style={{ marginLeft: 8, color: '#faad14' }} />
              </Tooltip>
            )}
          </div>
        </Col>
      </Row>
    </Card>
  );

  // 渲染散点图配置
  const renderScatterConfig = () => (
    <Card title="散点图样式" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Text>图形标记</Text>
          <Select
            value={scatterConfig.symbol || 'circle'}
            onChange={(val) => updateScatterConfig('symbol', val)}
            style={{ width: '100%' }}
          >
            <Option value="circle">实心圆</Option>
            <Option value="rect">实心矩形</Option>
            <Option value="roundRect">实心圆角矩形</Option>
            <Option value="triangle">实心三角形</Option>
            <Option value="diamond">实心菱形</Option>
            <Option value="pin">实心水滴</Option>
            <Option value="arrow">实心箭头</Option>
          </Select>
        </Col>
        <Col span={8}>
          <Text>标记大小</Text>
          <InputNumber
            value={scatterConfig.symbolSize || 10}
            onChange={(val) => updateScatterConfig('symbolSize', val)}
            min={1}
            max={50}
            style={{ width: '100%' }}
          />
        </Col>
      </Row>
    </Card>
  );

  // 渲染雷达图配置
  const renderRadarConfig = () => (
    <Card title="雷达图样式" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Text>标记大小</Text>
          <InputNumber
            value={radarConfig.symbolSize || 4}
            onChange={(val) => updateRadarConfig('symbolSize', val)}
            min={1}
            max={20}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>线宽</Text>
          <InputNumber
            value={radarConfig.lineStyle?.width || 2}
            onChange={(val) => updateRadarConfig('lineStyle.width', val)}
            min={1}
            max={10}
            style={{ width: '100%' }}
          />
        </Col>
        <Col span={8}>
          <Text>
            填充区域透明度
            <Tooltip title="填充区域的透明度，0为完全透明，1为不透明">
              <InfoCircleOutlined style={{ marginLeft: 8, fontSize: 14 }} />
            </Tooltip>
          </Text>
          <InputNumber
            value={radarConfig.areaStyle?.opacity || 0.2}
            onChange={(val) => updateRadarConfig('areaStyle.opacity', val)}
            min={0}
            max={1}
            step={0.1}
            style={{ width: '100%' }}
          />
        </Col>
      </Row>
    </Card>
  );

  // 预设面板内容
  const presetsContent = (
    <Card title="预设样式" size="small" bordered={false}>
      <Space direction="vertical" style={{ width: '100%' }}>
        {presets.map((preset) => (
          <Button 
            key={preset.name}
            type={activePreset === preset.name ? 'primary' : 'default'}
            block
            onClick={() => applyPreset(preset.name)}
          >
            {preset.name}
          </Button>
        ))}
        {presets.length === 0 && <Text>暂无预设</Text>}
      </Space>
    </Card>
  );

  return (
    <div className="theme-series-config">
      <Tabs 
        type="card"
        defaultActiveKey="config"
        tabBarExtraContent={
          <Space>
            <Tooltip title="将当前配置保存为预设">
              <Button 
                icon={<SaveOutlined />}
                onClick={() => setIsPresetModalVisible(true)}
              >
                保存预设
              </Button>
            </Tooltip>
          </Space>
        }
      >
        <TabPane tab="图表配置" key="config">
          <div style={{ marginBottom: 16 }}>
            <Group value={chartType} onChange={(e) => setChartType(e.target.value)}>
              <RadioButton value="line">折线图</RadioButton>
              <RadioButton value="bar">柱状图</RadioButton>
              <RadioButton value="pie">饼图</RadioButton>
              <RadioButton value="scatter">散点图</RadioButton>
              <RadioButton value="radar">雷达图</RadioButton>
            </Group>
          </div>

          <Row gutter={[16, 0]}>
            <Col span={18}>
              {chartType === 'line' && renderLineConfig()}
              {chartType === 'bar' && renderBarConfig()}
              {chartType === 'pie' && renderPieConfig()}
              {chartType === 'scatter' && renderScatterConfig()}
              {chartType === 'radar' && renderRadarConfig()}
            </Col>
            <Col span={6}>
              {presetsContent}
            </Col>
          </Row>
        </TabPane>
      </Tabs>

      {/* 保存预设对话框 */}
      <Modal
        title="保存预设"
        open={isPresetModalVisible}
        onOk={handleSavePreset}
        onCancel={() => setIsPresetModalVisible(false)}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Text>请为当前配置命名：</Text>
          <Input 
            placeholder="输入预设名称" 
            value={presetName}
            onChange={(e) => setPresetName(e.target.value)}
            maxLength={20}
          />
          <Text type="secondary">
            <QuestionCircleOutlined /> 预设将仅保存当前图表类型（{chartType}）的样式配置
          </Text>
        </Space>
      </Modal>
    </div>
  );
};

export default SeriesConfig;